package com.android.ailaoshan.tools;

import com.android.ailaoshan.user.handle.LoginHandler;
import com.android.ailaoshan.user.model.RecorderInfo;

import org.litepal.LitePal;

import java.util.List;
import java.util.Map;

/**
 * 管理记录信息
 */
public class ManagerRecorder {

    /**
     * 查询未完成的记录ID
     */
    public long getUnfinishedId(){
        List<RecorderInfo> recorderInfoList = LitePal.where("isOver = ?","false").find(RecorderInfo.class);
        if(recorderInfoList.size() > 0){
            // 返回第一条未完成的记录
            return recorderInfoList.get(0).getrId();
        }
        // 不存在未完成的记录，则新建一条记录
        long rId = System.currentTimeMillis();
        newRecorder(rId);
        return rId;
    }

    /**
     * 新建一条记录
     */
    private void newRecorder(long rId){
        new Thread(
            ()->{
                // 获取用户名
                BaseApplication baseApplication = BaseApplication.getInstance();
                LoginHandler loginHandler = new LoginHandler(baseApplication.getbContext());
                Map<String,String> userMap = loginHandler.getData();
                String userName = userMap.get("userName");

                RecorderInfo recorderInfo = new RecorderInfo();
                if(userName.equals("")){
                    recorderInfo.setrUser("custom");
                }else{
                    recorderInfo.setrUser(userName);
                }
                recorderInfo.setrId(rId);
                recorderInfo.setrTime(System.currentTimeMillis());
                recorderInfo.setOver(false);

                recorderInfo.save();
            }
        ).start();
    }

    /**
     * 查询已完成的记录ID
     */
    public List<RecorderInfo> getFinishedId(){
        return LitePal.where("isOver = ?","true").find(RecorderInfo.class);
    }
}
